#!/bin/bash
# My first script
for area in 5 2 3
do
    ## set dte variable to the date from which u want to record weather data
    dte="2012/09/10"
    echo $dte
    ## run for loop up to number of days for which u want data
    for i in {1..30}
    do
	vardate=`date +"%Y/%m/%d" --date "$dte $i days"`
	varDay=`echo $vardate | cut -c 9-10`

	varMonth=`echo $vardate | cut -c 6-7`

	varYear=`echo $vardate | cut -c 1-4`
	echo $varYear $varMonth $varDay
	wget -O $varDay.html "http://www.cse.iitb.ac.in/room-scheduler/day.php?day=$varDay&month=$varMonth&year=$varYear&area=$area"
	html2text $varDay.html >$varDay.txt
	rm $varDay.html
	sed '1,35d' $varDay.txt| sed 's/\[//g' | sed 's/\]//g' | sed 's/new.gif//g'>1.txt #This will remove top 35 lines, these lines are noise
	sed '/<<Go_To_Day_Before Go/,/$d/d' 1.txt |sed -n /[0-2][0-9]:[0-9][0-9]/p |sed 's/|__*/| 0 /g' |sed 's/|   */| 0 /g' |sed 's/|[^|0]*|/| 1 |/g'|sed 's/|[^012 ][^|]*|/| 1 |/g'>$varDay.txt 
    #this will remove bottom lines with noise
	rm 1.txt
	var="23:45:00"
	rm temp.txt
	fieldNo=`awk 'BEGIN {FS="|"} END {print NF}'  $varDay.txt`
	for j in {1..32} #this for loop will be used for filling in the data from 12 am to 8am
	do
	    before=`date --date "$var 15 minutes"`
	    var=`echo $before| cut -c 12-19`
	    if [ $fieldNo -eq 7 ]; then
		echo $vardate"_"$var "0 0 0 0" >>temp.txt
            else
		echo $vardate"_"$var "0 0 0" >>temp.txt
            fi	

	done
	export vardate=$vardate
	awk -F'|' '{ print ENVIRON["vardate"]"_"$2":00"$3 $4 $5 $6}' $varDay.txt >temp1.txt 
	cat temp1.txt | sed 's/  / /g'>tempRoom.txt #denoising the data
	cat tempRoom.txt | awk '{print $0; print $0}'>>temp.txt
	rm temp1.txt tempRoom.txt
	
	cat temp.txt >> floor$area.txt
	rm $varDay.txt
    done
done #foor loop for area completes
awk '{print $2" "$3" "$4" "$5" "$6}' floor2.txt >1.txt
awk '{print $2" "$3" "$4" "$5" "$6}' floor3.txt >2.txt
paste floor5.txt 1.txt 2.txt >floor2.txt
#cat 1.txt | sed 's/  */ /g' >RoomSchedule.txt
awk  '{gsub(" \t"," ",$0); print;}' floor2.txt > floor3.txt #replace <space TAB> with <space>
awk  '{gsub("\t"," ",$0); print;}' floor3.txt > RoomSchedule.txt #replace <space TAB> with <space>
rm 1.txt 2.txt floor2.txt floor3.txt floor5.txt

#------------------------------------------------------------
date2stamp () {
    date --utc --date "$1" +%s
}
dateDiff (){
    case $1 in
        -s)   sec=1;      shift;;
        -m)   sec=60;     shift;;
        -h)   sec=3600;   shift;;
        -d)   sec=86400;  shift;;
        *)    sec=86400;;
    esac
    dte1=$(date2stamp $1)
    dte2=$(date2stamp $2)
    diffSec=$((dte2-dte1))
    if ((diffSec < 0)); then abs=-1; else abs=1; fi
    echo $((diffSec/sec*abs))
}
